//
//  CoreDataManager.swift
//  MyCloset
//
//  Created by 牟好好 on 2024/10/24.
//

import SwiftUI
import CoreData

class CoreDataViewModel: ObservableObject {
    static let shared = CoreDataViewModel()
    
    let container: NSPersistentContainer
    @Published var savedEntities: [ClothesEntity] = []
    
    init() {
        container = NSPersistentContainer(name: "MyCloset")
        container.loadPersistentStores { description, err in
            if let err = err {
                print( "加载错误\(err)")
            }
        }
        fetchClothes()
    }
    
    func fetchClothes() {
        let request = NSFetchRequest<ClothesEntity>(entityName: "ClothesEntity")
        do {
            savedEntities = try container.viewContext.fetch(request)
        } catch let error {
            print("查找失败 \(error)")
        }
    }
    
    func addClothes(id: UUID, imageURL: String, features: String) {
        let newClothes = ClothesEntity(context: container.viewContext)
        newClothes.id = id
        newClothes.imageURL = imageURL
        newClothes.features = features
        
        saveData()
    }
    
    func saveData() {
        do {
            try container.viewContext.save()
            //查找新的数组数据，实时更新
            fetchClothes()
        } catch let error {
            print("保存失败 \(error)")
        }
    }
    
    func deleteClothes(indexSet: IndexSet) {
        guard let index = indexSet.first else { return }
        let entity = savedEntities[index]
        container.viewContext.delete(entity)
        saveData()
    }
    
    // 删除所有数据
    func deleteAllClothes() {
        let fetchRequest: NSFetchRequest<NSFetchRequestResult> = ClothesEntity.fetchRequest()
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)

        do {
            try container.viewContext.execute(deleteRequest)
            // 清空本地数组以反映数据变化
            savedEntities.removeAll()
            saveData()
        } catch let error {
            print("删除失败 \(error)")
        }
    }
}
